/**
 * 
 */
package com.xpec.c4.game.system;

import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ms.game.bank.db.CashLogModel;
import com.ms.game.common.utility.SimpleTimer;
import com.ms.game.common.utility.xxx;
import com.xpec.c4.db.hibernate.manager.HibernateDAOUtil;
import com.xpec.c4.db.hibernate.manager.HibernateLogManager;
import com.xpec.c4.game.utility.GUIDFactory;
import com.xpec.c4.game.utility.GameUtility;
import com.xpec.c4.game.utility.ProcessSpeedCalculator;

/**
 * 單純用來測試 bin 檔載入是否正常的 main class
 * 
 * @author TW15010
 */
public class InitDataTester {
	/**
	 * VM argument: -Dlog4j.configurationFile="./config/log4j2.xml"
	 * -DlogName=serverAll
	 */
	public static void main(String[] args) {
		Log log = LogFactory.getLog(InitDataTester.class);

		InitData.initAll();

		GUIDFactory.setProcessId(1);
		GUIDFactory.setWorldId(1);

		HibernateLogManager.getSession();
		HibernateLogManager.endSession();

		if (log.isInfoEnabled()) {
			log.info("count size ...");
		}

		int totalDataCount = HibernateDAOUtil.getLogDAO().getRowCount(CashLogModel.class, null);
		if (log.isInfoEnabled()) {
			log.info("total: " + totalDataCount);
		}

		Session session = HibernateLogManager.getSession();
		//Query q = session.createQuery("from CashLogModel where eventTime >= '2017/8/1 00:00:00' order by gameTime");
		//Query q = session.createQuery("from CashLogModel where eventTime between '2016/7/1 00:00:00' and '2016/7/31 00:00:00' order by eventTime");

		//Query q = session.createQuery("from CashLogModel order by eventTime");
		Query q = session.createQuery("from CashLogModel order by gameTime");

		q.setFetchSize(1000);
		ScrollableResults results = q.scroll(ScrollMode.FORWARD_ONLY);

		SimpleTimer timer = new SimpleTimer();
		timer.startByRemainTime(1000);

		ProcessSpeedCalculator psc = new ProcessSpeedCalculator();
		psc.setEstimateTotalProcCount(totalDataCount);
		psc.start();

		HashMap<String, CashLogModel> accountCashLogMap = new HashMap<String, CashLogModel>();

		while (results.next()) {
			Object[] rows = results.get();
			if (rows[0] instanceof CashLogModel) {
				CashLogModel model = (CashLogModel) rows[0];

				if (model.getCashChangeValue() > 0) {
					CashLogModel storedModel = accountCashLogMap.get(model.getAccountId());
					
					boolean isRobot = false;
					if(model.getChangeWay() == 4 || model.getChangeWay()==-4){
						isRobot = true;
					}
					
					if (!isRobot) {
						// 有上一筆資料
						if (storedModel != null) {
							// 目前的起始 != 上一筆的結餘
							if (model.getCashBeforeChange() != storedModel.getCashAfterChange()) {
								// 上一筆結餘是 0
								if (log.isInfoEnabled()) {
									log.info("");
									log.info(modelToString(storedModel));
									log.info(modelToString(model));
								}
							}
						}
					}

					accountCashLogMap.put(model.getAccountId(), model);
				}

//				if (model.getCashChangeValue() > 0) {
//					CashLogModel storedModel = accountCashLogMap.get(model.getAccountId());
//					// 有上一筆資料
//					if (storedModel != null) {
//						// 目前的行為是扣點
//						if (model.getChangeWay() < 0) {
//							// 上一筆結餘是 0
//							if (storedModel.getCashAfterChange() == 0) {
//								if (log.isInfoEnabled()) {
//									log.info("");
//									log.info(modelToString(storedModel));
//									log.info(modelToString(model));
//								}
//							}
//						}
//					}
//
//					accountCashLogMap.put(model.getAccountId(), model);
//				}
			}

			psc.increaseProcCount();
			if (timer.update()) {
				psc.calculateSpeed();

				if (log.isInfoEnabled()) {
					log.info(totalDataCount + " / " + psc.getTotalProcCount() + " speed: " + psc.getProcSpeed()
							+ "/sec remainTime: " + GameUtility.remainTimeToString(psc.getRemainTime()));
				}

				timer.restart();
			}

			if ((psc.getTotalProcCount() % 1000) == 0) {
				session.clear();
			}
		}

		results.close();
		HibernateLogManager.endSession();
	}

	public static String modelToString(CashLogModel model) {
		if (model == null) {
			return "";
		}

		StringBuilder sb = new StringBuilder();
		sb.append(GameUtility.timeToString(model.getEventTime().getTimeInMillis(), GameUtility.TIME_FORMAT_FULL));
		sb.append("\t");
		sb.append(model.getOpenId());
		sb.append("\t");
		sb.append(model.getAccountId());
		sb.append("\t");
		sb.append(model.getChangeWayDesc());
		sb.append("\t");
		sb.append(model.getCashBeforeChange());
		sb.append("\t");
		sb.append(model.getCashChangeValue());
		sb.append("\t");
		sb.append(model.getCashAfterChange());

		return sb.toString();
	}
}
